#!/bin/sh
#
# gateway-daemon:  OTA update & daemon launcher
#
# chkconfig: 345 99 01
# description:  Gateway daemon with OTA update handling
#
# processname: gateway
# pidfile: /var/run/gateway.pid
#

# 配置路径
OTA_PATH=/usr/bin/gateway_txt.update
EXE_PATH=/usr/bin/gateway_txt
BAK_PATH=/usr/bin/gateway_txt.bak
PID_FILE=/var/run/gateway_txt.pid

# 启动函数
start() {
    printf "Starting gateway daemon: "

    # OTA 更新逻辑
    if [ -f "$OTA_PATH" ]; then
        echo "OTA update found, updating executable..."
        [ -f "$EXE_PATH" ] && mv "$EXE_PATH" "$BAK_PATH"
        mv "$OTA_PATH" "$EXE_PATH"
        chmod +x "$EXE_PATH"
    fi

    # 检查是否已有守护进程运行
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if kill -0 "$PID" 2>/dev/null; then
            echo "already running (pid $PID)"
            return 0
        fi
    fi

    # 启动后台守护进程
    if [ -f "$EXE_PATH" ]; then
        "$EXE_PATH" &
        echo $! > "$PID_FILE"
        echo "done (pid $(cat $PID_FILE))"
    else
        echo "Error: $EXE_PATH not found!"
        return 1
    fi
}

# 停止函数
stop() {
    printf "Stopping gateway daemon: "
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        kill "$PID" 2>/dev/null
        rm -f "$PID_FILE"
        echo "done"
    else
        echo "No running daemon found"
    fi
}

# 重启函数
restart() {
    stop
    sleep 1
    start
}

# 命令行参数处理
case "$1" in
    start) start ;;
    stop) stop ;;
    restart) restart ;;
    *) echo "Usage: $0 {start|stop|restart}" ;;
esac

exit 0
